{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "name：曾露莎"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-698ada706af1>:3: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /home/lusha/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /home/lusha/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /home/lusha/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/lusha/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/lusha/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#数据准备\n",
    "xs = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义参数\n",
    "#结点数\n",
    "layer1_node=200\n",
    "layer2_node=60\n",
    "#正则参数\n",
    "lamda=0.0001\n",
    "#学习率\n",
    "learning_rate_base=0.8\n",
    "global_step= tf.Variable(0,trainable=False)\n",
    "learning_rate_decay=0.99\n",
    "#一个batch的训练数目\n",
    "batch_size=200"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#可变学习率\n",
    "learning_rate=tf.train.exponential_decay(learning_rate_base,global_step,600,learning_rate_decay)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义一个用于计算隐层和输出层y的函数，当隐层数目改变要更新\n",
    "\n",
    "def add_layer(inputs, weight, bias, activation_function=None):\n",
    "    loc_y = tf.matmul(inputs, weight) + bias\n",
    "    if activation_function is None:\n",
    "        loc_outputs = loc_y\n",
    "    else:\n",
    "        loc_outputs = activation_function(loc_y)\n",
    "    return loc_outputs\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "#暂时加2层\n",
    "# 添加隐藏层，隐层1的系数\n",
    "weight1 =tf.Variable(tf.truncated_normal([784,layer1_node],stddev=0.1))\n",
    "bias1=tf.Variable(tf.truncated_normal([layer1_node]))\n",
    "# 添加隐藏层，隐层2的系数\n",
    "weight2 =tf.Variable(tf.truncated_normal([layer1_node,layer2_node],stddev=0.1))\n",
    "bias2=tf.Variable(tf.truncated_normal([layer2_node]))\n",
    "# 添加隐藏层，输出层的系数  \n",
    "weight3 =tf.Variable(tf.truncated_normal([layer2_node,10],stddev=0.1))\n",
    "bias3=tf.Variable(tf.truncated_normal([10]))                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "#计算预测输出\n",
    "#隐层1输出,激活函数用sigmoid\n",
    "output_layer1=add_layer(xs, weight1, bias1, activation_function=tf.nn.tanh)\n",
    "#隐层2输出,激活函数用sigmoid\n",
    "output_layer2=add_layer(output_layer1, weight2, bias2, activation_function=tf.nn.tanh)\n",
    "#输出层y\n",
    "y=add_layer(output_layer2, weight3, bias3, activation_function=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-9-7dfed5996e70>:3: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#计算加入正则的损失函数\n",
    "#计算交叉熵\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "#正则L2,层数改变时要更新\n",
    "regularizer = tf.contrib.layers.l2_regularizer(lamda)\n",
    "regularization = regularizer(weight1)+regularizer(weight2)+regularizer(weight3)\n",
    "#总的损失函数\n",
    "loss = cross_entropy+regularization\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "#生成step，\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.1137\n",
      "0.9697\n",
      "0.9768\n",
      "0.9776\n",
      "0.9763\n",
      "0.981\n",
      "0.9805\n",
      "0.9802\n",
      "0.9822\n",
      "0.9809\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for i in range(10000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "    sess.run(train_step, feed_dict={xs: batch_xs, y_: batch_ys})\n",
    "    if i % 1000 == 0:\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "        print(sess.run(accuracy, feed_dict={xs: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.6766176\n"
     ]
    }
   ],
   "source": [
    "print(sess.run(learning_rate))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10000\n"
     ]
    }
   ],
   "source": [
    "print(sess.run(global_step))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9806\n",
      "[ True  True  True ...  True  True  True]\n",
      "0.9998\n"
     ]
    }
   ],
   "source": [
    "# Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "print(sess.run(accuracy, feed_dict={xs: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))\n",
    "print(sess.run(correct_prediction, feed_dict={xs: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))\n",
    "\n",
    "print(sess.run(accuracy, feed_dict={xs: mnist.train.images,\n",
    "                                      y_: mnist.train.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7rc1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
